//
//  BusinessCenterViewController.m
//  联付商圈
//
//  Created by 韩佳睿 on 2017/8/12.
//  Copyright © 2017年 lianfu. All rights reserved.
//

#import "BusinessCenterViewController.h"
#import "WalletTableViewCell.h"
#import "RealNameAuthenticationViewController.h"
#import "SafeCenterTableViewController.h"
#import "ReceiptViewController.h"
#import "联付商圈-Swift.h"
#import "YYModel.h"
#import "UserHeaderView.h"
#import "LoginViewController.h"

@interface BusinessCenterViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate, UserHeaderViewDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, retain)NSArray *walletLbArr;
@property (nonatomic, retain)NSArray *imageArr;
@property (nonatomic ,strong)UITableView *walletTab;
@property (nonatomic, strong)UILabel *titleLabel;
@property (nonatomic, strong)UserHeaderView *headerView;

@end

@implementation BusinessCenterViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    [self prepareData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
}

- (void)makeUI{
    
    self.view.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    _walletTab = [[UITableView alloc]initWithFrame:CGRectMake(0,-20, SCREENW, SCREENH)style:UITableViewStyleGrouped];
    _walletTab.delegate = self;
    _walletTab.dataSource = self;
    _walletTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _walletTab.rowHeight = 50;
    [_walletTab registerClass:[WalletTableViewCell class] forCellReuseIdentifier:@"walletCell"];
    _walletTab.sectionHeaderHeight = 5;
    [self.view addSubview:_walletTab];
    
    self.headerView = [UserHeaderView viewFromXib];
    self.headerView.delegate = self;
    if (_userModel) {
        [self.headerView renderViewWithUserModel:_userModel];
    } else {
        NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        SQUserModel *model = [SQUserModel yy_modelWithDictionary:dic];
        [self.headerView renderViewWithUserModel:model];
    }
    _walletTab.tableHeaderView = _headerView;
    _walletTab.bounces = NO;
}

- (void)prepareData {
    
    self.titleLabel.text= @"商户中心";
    self.imageArr = @[@"shimingrenzhengimage", @"wallet", @"order", @"safe",  @"shop", @"something", @"orderManager" , @"about", @"exit"];
    self.walletLbArr = @[@"实名认证", @"我的钱包", @"我的订单", @"安全中心", @"店铺管理", @"商品管理", @"订单管理",@"关于联付商圈",@"安全退出"];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults]objectForKey:@"userInfo"];
    SQUserModel *model = [SQUserModel yy_modelWithDictionary:dic];
    if (model) {
        [self refreshDataWithFinishBlock:^(NSDictionary *userDic, NSError *error) {
            self.userModel = [SQUserModel yy_modelWithDictionary:userDic[@"success"]];
            [self.walletTab reloadData];
        }];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.walletLbArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WalletTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"walletCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor = [UIColor whiteColor];
    
    if (indexPath.row == 0) {
        cell.contentLb.text = _userModel.isRealName;
    }else if (indexPath.row == 1){
        if (_userModel.money) {
            cell.contentLb.text = [NSString stringWithFormat:@"%@元", _userModel.money];
        } else {
            cell.contentLb.text = @"";
        }
    }else if (indexPath.row == 2){
        
    }else if (indexPath.row == 3) {
        cell.contentLb.text = @"保护中";
    } else if (indexPath.row == 8) {
        cell.lineView.hidden = YES;
    }
    cell.leftImageView.image = [UIImage imageNamed:[_imageArr objectAtIndex:indexPath.row]];
    cell.walletLabel.text = [_walletLbArr objectAtIndex:indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_userModel) {
        if (indexPath.row == 0) {
            if ([_userModel.isRealName isEqualToString:@"未认证"]) {
                RealNameAuthenticationViewController *vc = [RealNameAuthenticationViewController new];
                vc.userModel = _userModel;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else if (indexPath.row == 1){
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            QianbaoViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"QianbaoViewController"];
            [vc setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:vc animated:YES];
            
        }else if (indexPath.row == 2){
            
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            JiluViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"JiluViewController"];
            [vc setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 3){
            SafeCenterTableViewController *safeVC = [SafeCenterTableViewController new];
            [self.navigationController pushViewController:safeVC animated:YES];
        }else if (indexPath.row == 4) {
            if ([_userModel.isRealName isEqualToString:@"审核通过"]) {
                UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                TianjiadianpuTableViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"TianjiadianpuTableViewController"];
                [vc setHidesBottomBarWhenPushed:YES];
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                [self isRealNameAlertView];
            }
        } else if (indexPath.row == 5) {
            if ([_userModel.isRealName isEqualToString:@"审核通过"]) {
                UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                BianjishangpinViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"BianjishangpinViewController"];
                [vc setHidesBottomBarWhenPushed:YES];
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                [self isRealNameAlertView];
            }
        } else if (indexPath.row == 6) {
            if ([_userModel.isRealName isEqualToString:@"审核通过"]) {
                UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                ShangjiaDingdanGuanliViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"ShangjiaDingdanGuanliViewController"];
                [vc setHidesBottomBarWhenPushed:YES];
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                [self isRealNameAlertView];
            }
        }else if (indexPath.row == 7) {
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            GuanyvTableViewController * vc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"GuanyvTableViewController"];
            [vc setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:vc animated:YES];
            
        } else if (indexPath.row == 8) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil  message:@"确定要退出当前账户？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userInfo"];
                [self cleanView];
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil  message:@"请登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)cleanView {
    
    self.userModel = nil;
    [self.headerView renderViewWithUserModel:self.userModel];
    [self.walletTab reloadData];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
    
}
- (void)getMoneyCodeBtnClick{
    
    ReceiptViewController *receiptVc = [[ReceiptViewController alloc]init];
    [receiptVc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:receiptVc animated:YES];
    
}

- (void)loginAction {
    
    LoginViewController *loginVc = [LoginViewController new];
    [self.navigationController pushViewController:loginVc animated:YES];
}

- (void)changeAvatarAction {
    UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"本地相册",@"拍照", nil];
    sheet.tag = 1999;
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 1999)
    {
        if (buttonIndex == 2) {
            return;
        }
        else {
            UIImagePickerControllerSourceType sourceType;
            
            if (buttonIndex == 0)
            {
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                
            } else {
                sourceType = UIImagePickerControllerSourceTypeCamera;
            }
            
            if ([UIImagePickerController isSourceTypeAvailable: sourceType])
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.allowsEditing = YES;
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:^{
                    
                }];
            }
        }
    }
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self.headerView reloadAvatarWithImage:image];
    
    NSDictionary *param = @{@"name" : _userModel.userName};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    [manager POST:[Host stringByAppendingString:@"touxiang?"] parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.3);//进行图片压缩
        
        // 使用日期生成图片名称
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:[NSDate date]]];
        [formData appendPartWithFileData:imageData  name:@"photo" fileName:fileName mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
//        //打印下上传进度
//        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求成功
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)refreshDataWithFinishBlock:(void(^)(NSDictionary *userDic, NSError *error))finishBolok {
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    self.userModel = [SQUserModel yy_modelWithDictionary:dic];
    NSDictionary *param = @{@"name" : _userModel.userName, @"sfzh" : [[NSUserDefaults standardUserDefaults] objectForKey:@"password"], @"token" : @"220QWER181ASD1994ZXC"};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    [manager POST:[Host stringByAppendingString:@"shoploginout?"] parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if (dic[@"success"]) {
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:dic[@"success"] forKey:@"userInfo"];
            [userDefaults synchronize];
            
            if (finishBolok) {
                finishBolok(dic, nil);
            }
        } else {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = dic[@"error"][@"message"];
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:1.0];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (finishBolok) {
            finishBolok(nil, error);
        }
    }];
}

- (void)isRealNameAlertView {
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
    HUD.labelText = @"请去实名认证";
    HUD.mode = MBProgressHUDModeText;
    [HUD hide:YES afterDelay:1.0];
}

@end
